package mrh.niubi.librarysystem.controller;


import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
import mrh.niubi.librarysystem.common.Result;
import mrh.niubi.librarysystem.constants.Constants;
import mrh.niubi.librarysystem.pojo.UserBean;
import mrh.niubi.librarysystem.pojo.sobj.SendUser;
import mrh.niubi.librarysystem.service.UserService;
import mrh.niubi.librarysystem.service.impl.UserServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Random;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*")
public class UserApplication {

    @Autowired
    private UserService userService;

    private static String generateToken(int length){
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        String token = "";
        for (int i = 0; i < length; i++) {
            Random random = new Random();
            int randomIndex = random.nextInt(characters.length());
            token += characters.charAt(randomIndex);
        }
        return token;
    }

    @RequestMapping("/login")
    public Result login (@RequestParam String username, @RequestParam String password){
        UserBean user = userService.findById(username);
        if(user == null){
            return Result.error(Constants.CODE_403,"账号不存在");
        }
        else{
            if(Objects.equals(user.getPassword(), password)){
                SendUser sUser = BeanUtil.copyProperties(user,SendUser.class);
                sUser.setToken(generateToken(88));
                return Result.success(sUser);
            }
            else{
                return Result.error(Constants.CODE_403,"密码错误");
            }
        }
    }

    @RequestMapping("/reg")
    public Result reg(@RequestParam String username,@RequestParam String password){
        if(userService.findById(username) != null){
            return Result.error(Constants.CODE_403,"用户名已存在");
        }
        else {
            UserBean newuser = new UserBean(username,1L,password);
            userService.insertUser(newuser);
            return Result.success();
        }
    }

}
